import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/:pathMatch(.*)*',
    redirect: () => {
      // 如果未登录，跳转到 /login，否则跳转到 /home
      const isAuthorized = localStorage.getItem('token') // 或用 pinia 的 userStore
      return isAuthorized ? '/home' : '/login'
    }
  },
  { path: '/login', name: 'login', component: () => import('@/views/LoginRegisterView.vue') },
  { path: '/user/info', name: 'userInfo', component: () => import('@/views/UserInfoView.vue') },
  { path: '/user/settings', name: 'userSettings', component: () => import('@/views/UserSettingView.vue') },
  {
    path: '/',
    name: 'main',
    component: () => import('@/views/MainView.vue'),
    children: [
      { path: '', redirect: '/home' }, // 默认跳转到 home
      { path: 'home', name: 'home', component: () => import('@/views/HomeView.vue') },
      { path: 'inbox', name: 'inbox', component: () => import('@/views/InboxView.vue') },
      { path: 'sent', name: 'sent', component: () => import('@/views/SentView.vue') },
      { path: 'draft', name: 'draft', component: () => import('@/views/DraftView.vue') },
      { path: 'spam', name: 'spam', component: () => import('@/views/SpamView.vue') },
      { path: 'deleted', name: 'deleted', component: () => import('@/views/DeletedView.vue') },
      { path: 'compose', name: 'compose', component: () => import('@/views/ComposeView.vue') },
      {
        path: '/draft/compose/:draftId',
        name: 'DraftComView',
        component: () => import('@/views/DraftComView.vue'),
      },
      {
        path: 'mail/:id',
        name: 'mailDetail',
        component: () => import('@/views/MailDetailView.vue'),
      },
      {
        path: 'search',
        name: 'search',
        component: () => import('@/views/SearchView.vue'),
      },
    ],
  },
]

const router = createRouter({ history: createWebHistory(), routes })

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  if (!userStore.isAuthorized && to.path !== '/login') {
    next('/login')
  } else if (userStore.isAuthorized && to.path === '/login') {
    next('/')
  } else {
    next()
  }
})

export default router
